import { useState, useEffect } from 'react';
import {
    Box,
    Typography,
    TextField,
    Button,
    Paper,
    Divider,
    CircularProgress,
    Alert,
    Autocomplete,
    Chip,
    FormControl,
    MenuItem,
    Select,
    InputLabel,
    OutlinedInput,
    SelectChangeEvent
} from '@mui/material';
import { Search as SearchIcon } from '@mui/icons-material';
import Breadcrumb, { BreadcrumbItem } from '../../components/Breadcrumb';
import { getStudyAreas, getMajors, getPrograms, searchSchools, SearchSchoolsParams } from '../../api/recommendation';

// 面包屑导航配置
const breadcrumbItems: BreadcrumbItem[] = [{ title: '首页' }, { title: '选校推荐' }];

const SchoolRecommendation = () => {
    // 表单状态
    const [gpa, setGpa] = useState<string>('');
    const [selectedAreas, setSelectedAreas] = useState<string[]>([]);
    const [selectedMajor, setSelectedMajor] = useState<string>('');
    const [selectedProgram, setSelectedProgram] = useState<string>('');
    const [programInput, setProgramInput] = useState<string>('');

    // 选项列表状态
    const [areaOptions, setAreaOptions] = useState<string[]>([]);
    const [majorOptions, setMajorOptions] = useState<string[]>([]);
    const [programOptions, setProgramOptions] = useState<string[]>([]);

    // 推荐结果状态
    const [recommendationResult, setRecommendationResult] = useState<string[]>([]);

    // 加载状态
    const [loading, setLoading] = useState<boolean>(false);
    const [areaLoading, setAreaLoading] = useState<boolean>(false);
    const [majorLoading, setMajorLoading] = useState<boolean>(false);
    const [programLoading, setProgramLoading] = useState<boolean>(false);

    // 错误状态
    const [error, setError] = useState<string | null>(null);

    // 获取留学地区选项
    useEffect(() => {
        const fetchAreas = async () => {
            try {
                setAreaLoading(true);
                const areas = await getStudyAreas();
                setAreaOptions(areas);
            } catch (error) {
                console.error('获取留学地区选项失败:', error);
            } finally {
                setAreaLoading(false);
            }
        };

        fetchAreas();
    }, []);

    // 获取本科专业选项
    useEffect(() => {
        const fetchMajors = async () => {
            try {
                setMajorLoading(true);
                const majors = await getMajors();
                setMajorOptions(majors);
            } catch (error) {
                console.error('获取本科专业选项失败:', error);
            } finally {
                setMajorLoading(false);
            }
        };

        fetchMajors();
    }, []);

    // 处理留学项目输入变化
    useEffect(() => {
        const fetchPrograms = async () => {
            if (!programInput.trim()) {
                setProgramOptions([]);
                return;
            }

            try {
                setProgramLoading(true);
                const programs = await getPrograms(programInput);
                setProgramOptions(programs);
            } catch (error) {
                console.error('获取留学项目选项失败:', error);
            } finally {
                setProgramLoading(false);
            }
        };

        // 使用防抖处理输入
        const timer = setTimeout(() => {
            fetchPrograms();
        }, 300);

        return () => clearTimeout(timer);
    }, [programInput]);

    // 处理留学地区选择变化
    const handleAreaChange = (event: SelectChangeEvent<typeof selectedAreas>) => {
        const {
            target: { value }
        } = event;
        setSelectedAreas(
            // On autofill we get a stringified value.
            typeof value === 'string' ? value.split(',') : value
        );
    };

    // 处理本科专业选择变化
    const handleMajorChange = (event: SelectChangeEvent) => {
        setSelectedMajor(event.target.value);
    };

    // 处理查询
    const handleQuery = async () => {
        // 验证输入
        if (!gpa.trim()) return setError('请输入绩点');

        if (selectedAreas.length === 0) return setError('请选择至少一个留学地区');

        if (!selectedMajor) return setError('请选择本科专业');

        try {
            setLoading(true);
            setError(null);

            const params: SearchSchoolsParams = {
                cgpa: gpa,
                area: selectedAreas,
                major: selectedMajor,
                program: selectedProgram
            };

            const results = await searchSchools(params);
            setRecommendationResult(results);
        } catch (error) {
            console.error('获取推荐结果失败:', error);
            setError('获取推荐结果失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    let i = 0;
    const getOptionKey = (option: string) => {
        i++;
        return `${option}-${i}`;
    };

    return (
        <Box sx={{ p: { xs: 2, sm: 3 }, maxWidth: '1200px', mx: 'auto' }}>
            {/* 面包屑导航 */}
            <Box sx={{ mb: 3 }}>
                <Breadcrumb items={breadcrumbItems} />
            </Box>

            {/* 页面内容 */}
            <Box sx={{ display: 'flex', flexDirection: 'column' }}>
                {/* 标题 */}
                <Box
                    sx={{
                        width: '100%',
                        p: 2,
                        textAlign: 'center',
                        borderBottom: '1px solid #e0e0e0',
                        mb: 4,
                        display: { xs: 'block', md: 'none' }
                    }}>
                    <Typography variant="h6" sx={{ fontWeight: 'bold' }}>
                        SME CDC Student Management System
                    </Typography>
                </Box>

                {/* 表单区域 */}
                <Box sx={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
                    {/* 表单行 - 绩点和留学地区 */}
                    <Box
                        sx={{
                            display: 'flex',
                            flexWrap: 'wrap',
                            mb: 3,
                            justifyContent: 'center'
                        }}>
                        <Box
                            sx={{
                                display: 'flex',
                                alignItems: 'center',
                                mr: { xs: 0, sm: 4 },
                                mb: { xs: 2, sm: 0 },
                                width: { xs: '100%', sm: 'auto' }
                            }}>
                            <Typography
                                sx={{
                                    fontWeight: 'bold',
                                    mr: 2,
                                    minWidth: '80px',
                                    textAlign: 'right'
                                }}>
                                绩点
                            </Typography>
                            <TextField
                                placeholder="请输入绩点"
                                value={gpa}
                                onChange={(e) => setGpa(e.target.value)}
                                size="small"
                                sx={{ width: '220px' }}
                            />
                        </Box>
                        <Box
                            sx={{
                                display: 'flex',
                                alignItems: 'center',
                                width: { xs: '100%', sm: 'auto' }
                            }}>
                            <Typography
                                sx={{
                                    fontWeight: 'bold',
                                    mr: 2,
                                    minWidth: '80px',
                                    textAlign: 'right'
                                }}>
                                留学地区
                            </Typography>
                            <FormControl sx={{ width: '220px' }} size="small">
                                <Select
                                    multiple
                                    value={selectedAreas}
                                    onChange={handleAreaChange}
                                    input={<OutlinedInput />}
                                    renderValue={(selected) => (
                                        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                                            {selected.map((value) => (
                                                <Chip key={value} label={value} size="small" />
                                            ))}
                                        </Box>
                                    )}
                                    MenuProps={{
                                        PaperProps: {
                                            style: {
                                                maxHeight: 224,
                                                width: 250
                                            }
                                        }
                                    }}>
                                    {areaLoading ? (
                                        <MenuItem disabled>
                                            <CircularProgress size={20} />
                                        </MenuItem>
                                    ) : (
                                        areaOptions.map((area) => (
                                            <MenuItem key={area} value={area}>
                                                {area}
                                            </MenuItem>
                                        ))
                                    )}
                                </Select>
                            </FormControl>
                        </Box>
                    </Box>

                    {/* 表单行 - 本科专业和留学项目 */}
                    <Box
                        sx={{
                            display: 'flex',
                            flexWrap: 'wrap',
                            mb: 3,
                            justifyContent: 'center'
                        }}>
                        <Box
                            sx={{
                                display: 'flex',
                                alignItems: 'center',
                                mr: { xs: 0, sm: 4 },
                                mb: { xs: 2, sm: 0 },
                                width: { xs: '100%', sm: 'auto' }
                            }}>
                            <Typography
                                sx={{
                                    fontWeight: 'bold',
                                    mr: 2,
                                    minWidth: '80px',
                                    textAlign: 'right'
                                }}>
                                本科专业
                            </Typography>
                            <FormControl sx={{ width: '220px' }} size="small">
                                <Select value={selectedMajor} onChange={handleMajorChange} displayEmpty>
                                    <MenuItem value="" disabled>
                                        <em>请选择专业</em>
                                    </MenuItem>
                                    {majorLoading ? (
                                        <MenuItem disabled>
                                            <CircularProgress size={20} />
                                        </MenuItem>
                                    ) : (
                                        majorOptions.map((major) => (
                                            <MenuItem key={major} value={major}>
                                                {major}
                                            </MenuItem>
                                        ))
                                    )}
                                </Select>
                            </FormControl>
                        </Box>
                        <Box
                            sx={{
                                display: 'flex',
                                alignItems: 'center',
                                width: { xs: '100%', sm: 'auto' }
                            }}>
                            <Typography
                                sx={{
                                    fontWeight: 'bold',
                                    mr: 2,
                                    minWidth: '80px',
                                    textAlign: 'right'
                                }}>
                                留学项目
                            </Typography>
                            <Autocomplete
                                value={selectedProgram}
                                onChange={(event, newValue) => {
                                    setSelectedProgram(newValue || '');
                                }}
                                inputValue={programInput}
                                onInputChange={(event, newInputValue) => {
                                    setProgramInput(newInputValue);
                                }}
                                getOptionKey={getOptionKey}
                                options={programOptions}
                                loading={programLoading}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        placeholder="请输入留学项目"
                                        size="small"
                                        InputProps={{
                                            ...params.InputProps,
                                            endAdornment: (
                                                <>
                                                    {programLoading ? (
                                                        <CircularProgress color="inherit" size={20} />
                                                    ) : null}
                                                    {params.InputProps.endAdornment}
                                                </>
                                            )
                                        }}
                                    />
                                )}
                                sx={{ width: '220px' }}
                            />
                        </Box>
                    </Box>

                    {/* 查询按钮 */}
                    <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3, mb: 4 }}>
                        <Button
                            variant="contained"
                            color="primary"
                            size="large"
                            startIcon={loading ? <CircularProgress size={20} color="inherit" /> : <SearchIcon />}
                            onClick={handleQuery}
                            disabled={loading}
                            sx={{
                                minWidth: '200px',
                                py: 1
                            }}>
                            {loading ? '查询中...' : '查询'}
                        </Button>
                    </Box>

                    {/* 错误提示 */}
                    {error && (
                        <Alert severity="error" sx={{ mt: 2, mb: 2 }}>
                            {error}
                        </Alert>
                    )}

                    {/* 推荐结果 */}
                    <Box sx={{ mt: 2 }}>
                        <Typography variant="h6" sx={{ mb: 2, fontWeight: 'bold' }}>
                            推荐结果
                        </Typography>
                        <Paper variant="outlined" sx={{ overflow: 'hidden' }}>
                            {recommendationResult.length > 0 ? (
                                recommendationResult.map((school, index) => (
                                    <Box key={index}>
                                        {index > 0 && <Divider />}
                                        <Box
                                            sx={{
                                                p: 2,
                                                textAlign: 'center',
                                                '&:hover': {
                                                    backgroundColor: '#f5f5f5'
                                                }
                                            }}>
                                            <Typography variant="body1">{school}</Typography>
                                        </Box>
                                    </Box>
                                ))
                            ) : (
                                <Box
                                    sx={{
                                        p: 3,
                                        textAlign: 'center',
                                        color: 'text.secondary'
                                    }}>
                                    <Typography variant="body1">请输入查询条件并点击查询按钮</Typography>
                                </Box>
                            )}
                        </Paper>
                    </Box>
                </Box>
            </Box>
        </Box>
    );
};

export default SchoolRecommendation;
